package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;
    @Autowired
    RoleDao roleDao;
    private BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public User login(String username) {
        return userDao.login(username);
    }

    @Override
    public void add(User user, Integer[] roleIds) {
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userDao.add(user);
        for (Integer roleId : roleIds) {
            Map<String,Integer> map = new HashMap<>();
            map.put("uid",user.getId());
            map.put("rid",roleId);
            userDao.addRelation(map);
        }
    }

    @Override
    public void del(Integer id) {
        userDao.delRelation(id);
        userDao.del(id);
    }

    @Override
    public void update(User user, Integer[] roleIds) {
        userDao.delRelation(user.getId());
        for (Integer roleId : roleIds) {
            Map<String,Integer> map = new HashMap<>();
            map.put("uid",user.getId());
            map.put("rid",roleId);
            userDao.addRelation(map);
        }
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        userDao.update(user);
    }

    @Override
    public User find(Integer id) {
        User user = userDao.findById(id);
        return user;
    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        PageHelper.startPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize());
        Page<User> page = userDao.selectByCondition(queryPageBean.getQueryString());
        for (User user : page) {
            Integer id = user.getId();
            Set<Role> roles = roleDao.findRolesByUserId(id);
            user.setRoles(roles);
        }
        PageResult pageResult = new PageResult(page.getTotal(), page);
        return pageResult;
    }
}
